jQuery(function($){
	
	var equationsBack;
	
	var currentE;
	
	var equationValue;
	var equationRound = 0;
	var roundTimes;
	
	var equationType; 
	
	var equationEnd = 0;
	
	var equationRealOp;
	var equationA;
	var equationL;
	
	var allRight = 0;
	var allWrong = 0;
	
	//hidden something
	
	
	
	
	$('#btn_play').click(function(){
        
		//set to zero when start a new round
		equationRound = 0;
		allRight = 0;
		allWrong = 0;
		equationEnd = 0;
		
		
    	equationType = $('#gameType').val();
    	$('#btn_next_round').hide();
        	
        $.ajax({
        		url: indexPath+'?r=play/getEquation',
        		content: document.body,
        		data: {Equation:{'code': equationType}},
        		dataType: 'json',
        		type: 'post',
        		success: function(response){
        			console.log(response);
//        			console.log(response.e[0]);
        			
        			//June 18, 2011 BoyLee
        			//change equation getting method, get all equation one times.
        			
        			//get all equations back and use equationBack[0] - [19] to use it.
        			equationsBack = response.e;
        			
        			//get equation value
        			equationValue = response.value;
        			
        			//get times
        			roundTimes = response.times-1;
        			
        			//hide some elements like map select
        			$('#gameType, #btn_play').slideUp(300);
        			
        			//set Math value
        			displayMath();
        			
        			//show some div
        			$('#btn_next, #input_answer, #input_left').removeAttr('disabled');
        			
        			$('#math_display').show();
    				
        			$('#input_answer').focus();
        			
        		}});
        
    });
	
	
	
	//if press enter in answer or left input field
	$('#input_answer, #input_left').keydown(function(event){
		if(event.keyCode == 13){
			$('#btn_next').click();
		}
	});
	
	//next Question button press
	$('#btn_next').click(function(){
		if($('#input_answer').val() == '' ||$('#input_left').val() == ''){
			alert('no empty');
			$('#input_answer').focus();
		}else{
			
			if(equationRound < roundTimes){
				//normal mode just display.
				saveMath();
				
				//Empty input 
    			$('#input_answer').val('');
    			$('#input_left').val('0');
    			
    			$('#input_answer').focus();
    			
    			displayMath();
			}else{
				
				if(roundTimes == equationRound){
					//the last time of this round
					equationEnd = 1;
					saveMath();
					
					//disable something..
					//clear samething
					$('#input_left').val(0);
					$('#input_answer').val('');
					
					//disable input box and next question button
    				$('#btn_next, #input_answer, #input_left').attr({'disabled':'disabled'});
    				
    				//show the same round button
    				//show next round button
    				$('#btn_next_round').show();
					
				}else{
					//TODO after round end;
					alert('Round End');
				}
				
			}
			
		}
//		
		
	});
	
	
	//start a new round the same with this round without select again.
	$('#btn_next_round').click(function(){
		$('#btn_play').click();
	});
	
	//display math get via ajax
	function displayMath()
	{
		currentE = equationsBack[equationRound];
		
		console.log(currentE.F);
		
		if(currentE.F == null){
			alert('Now Re Equation needed.');
			window.location.reload(true);
		}
		//filled
		$('#equation_First').text(currentE.F);
//		console.log(currentE.id);
		equationRealOp = showOperator(Number(currentE.O));
		$('#equation_Operate').text(equationRealOp);
		
		$('#equation_Second').text(currentE.S);

		if(currentE.O < 4){
			$('#equation_Plus, #equation_Left').hide();
		}else{
			$('#equation_Plus, #equation_Left').show();
		}
		
	}
	
	//get user answer and save it.
	function saveMath()
	{
		//get values
		equationA = $('#input_answer').val();
		equationL = $('#input_left').val();
		
		//check answer input is empty of not.
		if(equationA == ''){
			//empty show a alert or some warnning
			alert('not empty!!');
			
		}else{
			
			//plus one to round times
			equationRound += 1;
			
			
			todayNumber = Number($('#today_q_num').text());
			$('#today_q_num').text(todayNumber+1);
			
			//prepare logs and do some
			var tmpString = '<li>'+currentE.F+equationRealOp+currentE.S+'='+equationA;
			if(currentE.O >3) {
				tmpString += '...'+equationL;
			}
			
			//Save
			$.ajax({
				url: indexPath+'?r=play/saveEquation',
        		content: document.body,
        		data: {Equation:{'F': currentE.F, 'O':currentE.O, 'S':currentE.S, 'A':equationA, 'L':equationL, 'id':currentE.id, 'typeCode':equationType}, MapEnd:equationEnd},
        		dataType: 'json',
        		type: 'post',
        		success: function(response){
//        			console.log(response);
        			
        			//get user money on page
        			userMoney = Number($('#user_money').text());
        			typeCount = Number($('#'+equationType+'_count').text());
        			if(typeCount === 0){
        				$('#type_count').append('<tr><td>New</td><td> <span id="'+equationType+'_count">1</span></td><td><span id="'+equationType+'_t_count">0</span></td><td><span id="'+equationType+'_f_count">0</span></td></p>'); 
        			}else{
        				$('#'+equationType+'_count').text(typeCount+1);
        			}
        			trueCount = Number($('#'+equationType+'_t_count').text());
        			falseCount = Number($('#'+equationType+'_f_count').text());
        			
        			if(response.tof === 1){
        				//get right number on page
        				rightNum = Number($('#today_right_num').text());
        				tmpString += ' || (√) Right || +'+equationValue;
        				
        				//change money
        				$('#user_money').text(userMoney+equationValue);
        				
        				//change right num
        				$('#today_right_num').text(rightNum+1);
        				
        				//change detail right
        				$('#'+equationType+'_t_count').text(trueCount+1);
        				
        				allRight += 1;
        			}else{
        				//get wrong number on page
        				wrongNum = Number($('#today_wrong_num').text());
        				
        				tmpString += ' || (x) Wrong || -'+equationValue*2;
        				
        				//change money
        				$('#user_money').text(userMoney-equationValue*2);
        				
        				//chenge wrong num
        				$('#today_wrong_num').text(wrongNum+1);
        				
        				//change detail wrong
        				$('#'+equationType+'_f_count').text(falseCount+1);
        				
        				allWrong += 1;
        			}
        			
        			tmpString += '</li>';
        			
        			$('#log_content').prepend(tmpString);
        			
        		}
			});
			
			
		}
		

	
		
	}
	
	
	//display operator
	function showOperator(numOp)
	{
	    switch (numOp){
	    
	    case 1:
	      return '+';
	      break;

	    case 2:
	      return '-';
	      break;

		case 3:
	      return '×';
	      break;

		case 4:
		  return '÷';
	      break;

	    default:
	      return '??';
		}
	}
	
});